package com.tgy.admin.util;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.time.LocalDateTime;

/**
 * @author tianguiyin
 * @version 1.0
 * @date 2022/6/23 21:05
 *
 * 处理自带的四个字段的
 */
@Component
public class BeanFieldUtils {

    @Resource
    private LoginUserHelp loginUserHelp;

    public <T> void add(T t) throws IllegalAccessException {
        Class<?> aClass = t.getClass();
        //java反射调用get方法获取对象里的值
        Field[] obj=aClass.getDeclaredFields();
        String userName = loginUserHelp.getLoginUser().getUser().getUserName();
        for (Field field : obj) {
            field.setAccessible(true);
            String name = field.getName();
            switch (name){
                case "createdBy":
                case "updatedBy":
                    field.set(t,userName);
                    break;
                case "createdTime":
                case "updatedTime":
                    field.set(t, LocalDateTime.now());
                    break;
            }
        }
    }

    public <T> void update(T t) throws IllegalAccessException {
        Class<?> aClass = t.getClass();
        //java反射调用get方法获取对象里的值
        Field[] obj=aClass.getDeclaredFields();
        String userName = loginUserHelp.getLoginUser().getUser().getUserName();
        for (Field field : obj) {
            field.setAccessible(true);
            String name = field.getName();
            switch (name){
                case "updatedBy":
                    field.set(t,userName);
                    break;
                case "updatedTime":
                    field.set(t, LocalDateTime.now());
                    break;
            }
        }
    }
}
